$().ready(function() {
	ifState()
	imageCreate()
	validateRule()
	inputChange()
	radioChange()

});

/**
 * 页面判断，展示不同的页面
 * state = '管理员'
 * state = '教师'
 * */
function ifState() {
	let state = $('#authority').val()
	if(state === '管理员') {
		$('.Administrator').show()
		$('.teacher').hide()
		$('input[name="publicity"][value="0"]').prop('checked', true);
	}else {
		$('input[name="publicity"][value="1"]').prop('checked', true);
		$('.teacher').show()
		$('.Administrator').hide()
	}
}

$.validator.setDefaults({
	submitHandler : function() {
		save();
	}
});

// 图片处理
function imageCreate() {
	$('#imgFil').click(function (){
		var imageUrl = $(this).attr('src');
		$('.overlay').toggleClass('active');
		$('.overlay img').attr('src', imageUrl);
	})
	$('.overlay').click(function() {
		$(this).removeClass('active');
	});

}


// 单选框注册事件
function radioChange() {
	let radios = document.getElementsByName('publicity');
	let radiosAll = document.getElementsByName('state');
	for (let i = 0; i < radios.length; i++) {
		radios[i].addEventListener('change', function() {
			if(this.value === '0') {
				$('#selectChange').show()
			}else {
				$('#selectChange').hide()
			}
		});
	}
	for (let i = 0; i < radiosAll.length; i++) {
		radiosAll[i].addEventListener('change', function() {
			if(this.value === '0') {
				$('#selectChanges').show()
			}else {
				$('#selectChanges').hide()
			}
		});
	}
}

//提交事件
function save() {
	let imgs = $('#imgAll').children().length
	let state = $('#authority').val()
	let  data = {};
	let type = window.location.href.split('?')[1].split('=')[1];
	let img = $('#imgFil').attr('src')
	let formData = $('#signupForm').serializeArray();

	if(imgs === 0) {
		layer.msg("请上传资源封面")
		return
	}

	$.each(formData, function(index, item) {
		data[item.name] = item.value;
	});
	data['introducePortrait'] = img
	state === '管理员' ? data['newType'] = type : ''
	state === '教师' ? data['state'] = '1' : '0'
	addFrom(data)

}

// 输入框事件
function inputChange() {
	$('#sort').blur(function() {
		let value = $(this).val();
		let data = {
			sort: ''
		}
		data.sort = value
		if(value !== ''){
			inputFrom(data)
		}

	});
}


//优先级接口
function inputFrom(data) {
	return new Promise(function (resolve, reject) {
		$.ajax({
			url: '/courses/effect',
			type: 'POST',
			contentType: 'application/json',
			data: JSON.stringify(data),
			success: function(response) {
				// 请求成功时的处理
				if(response.code !== '0') {
					layer.msg(response.msg);
					$('#sort').val('')
					return
				}
			},
			error: function(xhr, status, error) {
				// 请求失败时的处理
				layer.msg(error);
				resolve(error)
			}
		});
	})
}

// 新增资源接口
function addFrom(data) {

	return new Promise(function (resolve, reject) {
		$.ajax({
			url: '/courses/save',
			type: 'POST',
			contentType: 'application/json',
			data: JSON.stringify(data),
			success: function(response) {
				// 请求成功时的处理
				if(response.code !== '0') {
					layer.msg(response.msg);
				}else {
					let index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
					parent.layer.close(index);
					parent.reLoad();
				}

			},
			error: function(xhr, status, error) {
				// 请求失败时的处理
				layer.msg(error);
				resolve(error)
			}
		});
	})

}

function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
		rules : {
			name:{
				required : true
			},
			couName : {
				required : true
			},
			couIntroduce : {
				required : true
			},
            title : {
				required : true
			},
            content : {
				required : true
			}
		}
	})
}

// 上传
 layui.use('upload', function () {
        var upload = layui.upload;
        //执行实例
        upload.render({
            elem: '#btnUpload', //绑定元素
            url: 'http://10.3.0.64:9900/minio/uploadFile', //上传接口
            accept: 'file',
            done: function (r) {
				$('#imgAll').html(`<img src="${r.data}" id="imgFil"  style="max-width: 50%;height: auto;cursor: pointer;" />`)
				imageCreate()
            },
            error: function (r) {
                layer.msg(r.msg);
            }
        });
    });

//文字限制
function limitTextarea(element, maxLength) {
	if (element.value.length > maxLength) {
		element.value = element.value.slice(0, maxLength);
		layer.msg('文字超出限制');
	}
}